package mqtt.utils;

import sun.misc.BASE64Encoder;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class StringUtils {

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static String trim(Object obj) {
        return obj == null ? "" : obj.toString().trim();
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static boolean isEmpty(Object obj) {
        return obj == null || obj.toString().length() == 0;
    }

    /**
     * 对字节数组进行Base64编码
     *
     * @param data
     * @return Base64编码的字符串
     * @throws IOException
     */
    public static String toBase64(byte[] data) throws IOException {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    public static String md5(String input) throws NoSuchAlgorithmException {
        return md5(input, StandardCharsets.UTF_8);
    }

    /**
     * md5
     *
     * @param input
     * @param charset
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String md5(String input, Charset charset) throws NoSuchAlgorithmException {
        //
        MessageDigest md5 = MessageDigest.getInstance("MD5");

        // 加密
        byte[] md5Bytes = md5.digest(input.getBytes(charset));

        // hex
        return DatatypeConverter.printHexBinary(md5Bytes);
    }

}
